import axios from "axios";
import { Message } from "element-ui";

/* 向vue原型对象上添加 $http 变量；并为其添加一个公共接口地址url */
const $axios = axios.create({
    baseURL: 'http://localhost:3001/api'
  })
  //请求拦截器
  $axios.interceptors.request.use( config =>{
    //判断浏览器本地是否有Token
    if(localStorage.UserToken){
        //将拿到的Token放在请求头中
        config.headers.Authorization = localStorage.getItem('UserToken')
        console.log('请求拦截器Token  '  + config.headers.Authorization)   
     } 
     return config;
     
}, error =>{
        console.log(error)
        return error;
 })

//响应拦截器
$axios.interceptors.response.use( success =>{     
    //根据响应状态判断业务逻辑
    if( success.status && success.status == 200){

        //根据响应码判断业务逻辑
        if( success.status.code ==500 || success.status.code == 401 || success.status.code == 403){
            Message.error({
                message:success.data.message,               
            })
            return;
        }
        //其他情况是成功响应 判断是否返回信息
        if( success.data.message){
            Message.success({
                message:success.data.message,               
            })           
        }
        //console.log(success)
    }
    return success.data;
}, error =>{
    if(error.response.code ==504 || error.response.code ==404){
        Message.error({
            message:'服务器出错'               
        })
    }else if( error.response.code ==403){
        Message.error({
            message:'权限不足'               
        })
    }else if( error.response.code ==401){
        Message.error({
            message:'未登录'               
        })
    }else{
        if(error.response.data){
            Message.error({
                message: error.response.data       
            }) 
        }else{
            Message.error({
                message: '未知错误'               
            })
        }
        console.log(error)
    }
    return;
 })

export default $axios